import {
  getCurrentUserUsingGet,
  updateUserUsingPost,
  userLogoutUsingPost,
} from '@/services/api/sysUserController';
import { history } from '@@/core/history';
import { useModel } from '@umijs/max';
import { Avatar, Button, Form, FormProps, Input, message, Radio, Space, Spin } from 'antd';
import React, { useEffect, useState } from 'react';
import { flushSync } from 'react-dom';

const SysUserInfo: React.FC = () => {
  const [userInfo, setUserInfo] = useState<API.SysUserVO>({});

  const [userInfoForm] = Form.useForm();
  const [loading, setLoading] = useState<boolean>(true);

  const { setInitialState } = useModel('@@initialState');

  const onFinish: FormProps<API.SysUserUpdateRequest>['onFinish'] = async (values) => {
    try {
      const params: API.SysUserUpdateRequest = { id: userInfo.id, ...values };

      const res = await updateUserUsingPost(params);
      if (res.code === 0) {
        message.success('修改成功');
        if (
          params.userPassword !== undefined &&
          params.userPassword.length >= 8 &&
          params.checkPassword !== undefined &&
          params.checkPassword.length >= 8
        ) {
          flushSync(() => {
            setInitialState((s) => ({ ...s, currentUser: undefined }));
          });
          const res = await userLogoutUsingPost();
          message.warning('请重新登陆');
          if (res.code === 0) {
            history.push('/user/login');
          }
          return;
        }

        flushSync(() => {
          setInitialState((s: any) => ({
            ...s,
            currentUser: { ...params },
          }));
        });
        history.back();
      } else {
        message.error('修改失败' + res.message);
      }
    } catch (e: any) {
      // message.error('修改失败' + e.message);
    }
  };

  const onFinishFailed: FormProps<API.SysUserUpdateRequest>['onFinishFailed'] = (errorInfo) => {
    message.error('请按规则填写');
  };

  const loadUserInfo = async () => {
    setLoading(true);
    const res = await getCurrentUserUsingGet();
    if (res.code === 0) {
      setUserInfo(res.data as any);
      userInfoForm.setFieldsValue(res.data); // 动态设置表单值
    } else {
      message.error('数据加载失败！');
    }
    setLoading(false);
  };

  /**
   * 加载数据
   */
  useEffect(() => {
    loadUserInfo();
  }, []);

  return (
    <div id="SysUserInfoPage">
      <Spin spinning={loading}>
        <Form
          form={userInfoForm}
          name="userInfoForm"
          initialValues={userInfo}
          style={{
            maxWidth: 600,
            border: '2px solid #f0f0f0', // 边框样式
            borderRadius: '3%',
            boxShadow: '0 4px 8px rgba(0, 0, 0, 0.1)', // 阴影样式
            padding: '5px',
          }}
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 16 }}
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
          autoComplete="off"
        >
          <div style={{ display: 'flex', justifyContent: 'center', margin: '5px 0 5px' }}>
            <Avatar style={{ width: 150, height: 150 }} src={userInfo.userAvatar} />
          </div>
          <Form.Item<API.SysUserUpdateRequest>
            label="头像地址"
            validateFirst={true}
            name="userAvatar"
            rules={[
              { type: 'url' },
              {
                validator: (_, value) => {
                  if (!value) return Promise.reject('请输入头像连接！');
                  // 校验通过后的回调
                  setUserInfo({ ...userInfo, userAvatar: value });
                  // 可以在这里调用外部函数

                  return Promise.resolve();
                },
              },
            ]}
          >
            <Input />
          </Form.Item>
          <Form.Item<API.SysUserUpdateRequest>
            label="用户名"
            name="userName"
            rules={[{ required: true, message: '请输入用户名!' }]}
          >
            <Input value="111" />
          </Form.Item>
          <Form.Item<API.SysUserUpdateRequest>
            label="性别"
            name="gender"
            rules={[{ required: true, message: '请选择性别!' }]}
          >
            <Radio.Group>
              <Radio value={0}> 男 </Radio>
              <Radio value={1}> 女 </Radio>
            </Radio.Group>
          </Form.Item>

          <Form.Item<API.SysUserUpdateRequest>
            label="邮箱"
            name="email"
            rules={[{ type: 'email' }]}
          >
            <Input />
          </Form.Item>

          <Form.Item<API.SysUserUpdateRequest>
            label="手机"
            name="phone"
            rules={[
              {
                pattern: /^1[3-9]\d{9}$/,
                message: '请输入正确的手机号格式',
              },
            ]}
          >
            <Input />
          </Form.Item>

          <Form.Item<API.SysUserUpdateRequest> label="密码" name="userPassword">
            <Input.Password />
          </Form.Item>

          <Form.Item<API.SysUserUpdateRequest> label="确认密码" name="checkPassword">
            <Input.Password />
          </Form.Item>

          <Form.Item label={null}>
            <Space>
              <Button type="primary" htmlType="submit">
                提交
              </Button>
              <Button type="default" onClick={() => loadUserInfo()}>
                重置
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Spin>
    </div>
  );
};

export default SysUserInfo;
